<template>
  <div class="page-view">
    <div class="map-view">
      <MyMap ref="myMap" >
        <MapMarker :data="data" :scale="0.7" :cluster="false"></MapMarker>
        <MapGeo v-if="layers" :json="layers" :stroke="{color: '#f0f',width: 2,}" ></mapgeo>
        <MapScale></MapScale>
      </MyMap>
    </div>
    <div class="map-leg">
      <template v-for="item in chartData">
        <div class="img" :key="item.title">
          <span class="map-leg-icon" :style="{background: item.color}"></span>
          <span>{{ item.title }}</span>
        </div>
      </template>
    </div>

    <div class="result-icon">
      <div class="icon-item"><a-icon type="bar-chart" :class="{ 'active': showChart }" @click="showChart = !showChart" /></div>
      <div class="icon-item"><a-icon type="table" :class="{ 'active': showTable}" @click="showTable = !showTable" /></div>
    </div>

    <!-- 筛选条件 -->
    <div class="search">
      <div class="btn-fetch">
        <a-button @click="showSearch = !showSearch">样点查询条件</a-button>
      </div>
      <div class="condition" v-if="showSearch">
        <a-form>
          <a-row :gutter="16">
            <a-col span="12">
              <a-form-item label="区域">
                <a-tree-select
                  v-model="searchForm.xzqdm"
                  style="width: 100%"
                  :treeData="city"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :replaceFields="{
                    value: 'dicCode',
                    label: 'dicValue'
                  }"
                  placeholder="请选择区域"
                  allow-clear
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col span="12">
              <a-form-item label="土地利用类型">
                <a-select v-model="searchForm.tdlylx" allow-clear placeholder="请选择">
                  <a-select-option value="02">园地</a-select-option>
                  <a-select-option value="03">林地</a-select-option>
                  <a-select-option value="04">草地</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col span="12">
              <a-form-item label="样点类型">
                <a-select v-model="searchForm.ydlx" allow-clear placeholder="请选择">
                  <a-select-option value="0">表层样</a-select-option>
                  <a-select-option value="1">剖面样</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col span="12">
              <a-form-item label="林地小班">
                <a-select v-model="searchForm.ldxb" allow-clear placeholder="请选择">
                  <a-select-option value="03">林地</a-select-option>
                  <a-select-option value="05">非林地</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col span="12">
              <a-form-item label="指标">
                <a-select v-model="searchForm.quota" allow-clear placeholder="请选择">
                  <template v-for="item in type">
                    <a-select-opt-group :key="item.text" :label="item.text">
                      <template v-for="option in item.children">
                        <a-select-option :key="option.value" :value="option.value">{{ option.text }}</a-select-option>
                      </template>
                    </a-select-opt-group>
                  </template>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col span="12">
              <a-form-item label="指标值">
                <a-row :gutter="8">
                  <a-col :span="11"><a-input v-model="searchForm.min" placeholder="最小值"></a-input></a-col>
                  <a-col :span="1">-</a-col>
                  <a-col :span="11"><a-input v-model="searchForm.max" placeholder="最大值"></a-input></a-col>
                </a-row>
              </a-form-item>
            </a-col>
            <a-col span="24">
              <a-form-item style="text-align: center;">
                <a-space>
                  <a-button type="primary" @click="searchHandler"> 查询 </a-button>
                  <a-button @click="showSearch = false"> 取消 </a-button>
                </a-space>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>

    <!-- 图表 -->
    <div class="chart-wrap" v-if="showChart">
      <div class="heaer-title">
        <div>土壤理化指标统计</div>
        <div class="close">
          <a-icon type="close" @click="showChart = false"></a-icon>
        </div>
      </div>
      <div class="chart-body">
        <a-spin :spinning="!chartData.length">
          <a-radio-group :options="CHART_TYPR" v-model="chartType" @change="onChangeChart" />
          <div class="chart-item">
            <Barchart :data="chartData"></Barchart>
          </div>
        </a-spin>
      </div>
    </div>

    <!-- 筛选结果 -->
    <a-drawer
      placement="bottom"
      :visible="showTable"
      :mask="false"
      @close="showTable = !showTable "
      :height="358"
      :bodyStyle="{padding: '8px 8px 0px 8px'}"
    >
      <div slot="title" class="deawer-title">
        <div>查询结果</div>
        <div style="margin-right: 40px;">
          <a-space>
            <a-button type="link" size="small" icon="filter" @click="showFiler = true">过滤</a-button>
            <a-button type="link" size="small" icon="download" @click="exportExcel">导出</a-button>
          </a-space>
        </div>
      </div>
      <a-table
        rowKey="ydbh"
        :loading="loading"
        :dataSource="data"
        size="small"
        :scroll="{ x: 'max-content' }"
        :bordered="false"
        :columns="columns"
        :pagination="pagination"
        :customRow="customRow"
      >
      </a-table>
    </a-drawer>

    <!-- 过滤条件 -->
    <a-modal
      title="过滤"
      v-model="showFiler"
      @ok="initFilter"
    >
      <div>
        <a-checkbox-group v-model="filterValue" style="width: 100%">
          <a-row>
            <template v-for="(item,key) in filters">
              <a-col :key="key" :span="12">
                <a-checkbox :value="key">{{ item }}</a-checkbox>
              </a-col>
            </template>
          </a-row>
        </a-checkbox-group>
      </div>
    </a-modal>

  </div>
</template>

<script>
import { TDLYLX, SFXZ, TQQK, QSLX, QSCD, PD, PXN, PX, MY, MZ, ZBLX, LFZLJJ, LCLDLX, LCCDLX } from '@/constant/index.js'
import { export_array_to_excel as exportArrayToExcel } from '@/utils/excel'
import { MyMap, MapMarker, MapGeo, MapScale } from '@/map'
import { queryAllcity, queryCityGeo, spatialQuery } from '@/api/common'
import { queryPointList } from '@/api/list'
import { queryiQuery } from '@/api/home'
import Barchart from './components/chart'
import { filters } from './filed'
import filedRange from './gra'
import { groupArrayByRange } from '../../utils/range'

// import yd from '@/assets/icon/yd.png'
// import ld from '@/assets/icon/ld.png'
// import cd from '@/assets/icon/cd.png'

// const MARKER_IMG = {
//   '02': 'rgba(38, 70, 83, 1)', // yd,
//   '03': 'rgba(41, 157, 144, 1)', // ld,
//   '04': 'rgba(232, 193, 107, 1)' // cd
// }

const CHART_TYPR = [
  {
    label: '有机质',
    value: 'om'
  },
  {
    label: '全氮',
    value: 'tn'
  },
  {
    label: '全磷',
    value: 'tp'
  },
  {
    label: '全钾',
    value: 'tk'
  },
  {
    label: '有效磷',
    value: 'ap'
  },
  {
    label: '速效钾',
    value: 'ak'
  },
  {
    label: '有效铁',
    value: 'afe'
  },
  {
    label: '有效锰',
    value: 'amn'
  },
  {
    label: '有效铜',
    value: 'acu'
  },
  {
    label: '有效锌',
    value: 'azn'
  },
  {
    label: '有效硼',
    value: 'ab'
  },
  {
    label: '有效钼',
    value: 'amo'
  }
]

const type = {
  lh: {
    text: '土壤理化性质',
    value: 'lh',
    children: [
      { text: '酸碱度', value: 'ph' },
      { text: '阳离子交换量', value: 'cec' }
    ]
  },
  yf: {
    text: '土壤养分',
    value: 'yf',
    children: [
      { text: '有机质', value: 'om' },
      { text: '全氮', value: 'tn' },
      { text: '全磷', value: 'tp' },
      { text: '全钾', value: 'tk' },
      { text: '有效磷', value: 'ap' },
      { text: '速效钾', value: 'ak' },
      { text: '有效硫', value: 'as1' }

    ]
  },
  hj: {
    text: '土壤环境',
    value: 'hj',
    children: [
      { text: '镉', value: 'cd' },
      { text: '汞', value: 'hg' },
      { text: '砷', value: 'as2' },
      { text: '铅', value: 'pb' },
      { text: '铬', value: 'cr' },
      { text: '镍', value: 'ni' }
    ]
  }
}

const columns = [
  {
    title: '序号',
    key: 'index',
    fixed: true,
    customRender: (text, record, index) => index + 1
  },
  {
    title: '样点编号',
    dataIndex: 'ydbh',
    fixed: true,
    key: 'ydbh'
  },
  {
    title: '标识码',
    dataIndex: 'bsm',
    key: 'bsm'
  },
  {
    title: '要素代码',
    dataIndex: 'ysdm',
    key: 'ysdm'
  },
  {
    title: '样点类别',
    dataIndex: 'ydlb',
    key: 'ydlb'
  },
  {
    title: '采样类型',
    dataIndex: 'cylx',
    key: 'cylx'
  },
  {
    title: '是否采集水稳性大团聚体',
    dataIndex: 'sfcjswxdtjt',
    key: 'sfcjswxdtjt'
  },
  {
    title: '坐落单位代码',
    dataIndex: 'zldwdm',
    key: 'zldwdm'
  },
  {
    title: '坐落单位名称',
    dataIndex: 'zldwmc',
    key: 'zldwmc"'
  },
  {
    title: '坡度',
    dataIndex: 'pd',
    key: 'pd"'
  },
  {
    title: '土地利用类型',
    dataIndex: 'tdlylx',
    key: 'tdlylx"'
  },
  {
    title: '土壤类型编码',
    dataIndex: 'trlxbm',
    key: 'trlxbm"'
  },
  {
    title: '土类',
    dataIndex: 'tl',
    key: 'tl"'
  },
  {
    title: '亚类',
    dataIndex: 'yl',
    key: 'yl"'
  },
  {
    title: '土属',
    dataIndex: 'ts',
    key: 'ts"'
  },
  {
    title: '土种',
    dataIndex: 'tz',
    key: 'tz"'
  }
]

export default {
  name: 'ListView',
  components: {
    MyMap,
    MapMarker,
    MapGeo,
    MapScale,
    Barchart
  },
  data () {
    this.filters = filters
    this.type = type
    this.TDLYLX = TDLYLX
    this.CHART_TYPR = CHART_TYPR
    this.SFXZ = SFXZ
    this.TQQK = TQQK
    this.QSLX = QSLX
    this.QSCD = QSCD
    this.PD = PD
    this.PXN = PXN
    this.PX = PX
    this.MY = MY
    this.MZ = MZ
    this.ZBLX = ZBLX
    this.LFZLJJ = LFZLJJ
    this.LCLDLX = LCLDLX
    this.LCCDLX = LCCDLX
    return {
      showSearch: false,
      city: [],
      layers: undefined,
      loading: false,
      showTable: true,
      searchForm: {
        xzqdm: undefined,
        tdlylx: undefined,
        ldxb: undefined,
        ydlx: undefined,
        quota: undefined,
        max: undefined,
        min: undefined
      },
      showFiler: false,
      filterValue: Object.keys(filters),
      columns,
      data: [],
      pagination: {
        pageSize: 5
      },
      showChart: true,
      chartType: 'om',
      chartData: [],
      showInfo: false,
      markerInfo: {}
    }
  },
  methods: {
    initMap (map) {
      console.log(map)
    },
    initFilter () {
      this.columns = this.filterValue.map(item => {
        return {
          title: filters[item],
          dataIndex: item,
          key: item
        }
      })
      this.showFiler = false
    },
    handleChange () {
      this.layers = undefined
      if (this.searchForm.xzqdm) {
        queryCityGeo({
          xzqdm: this.searchForm.xzqdm
        }).then(res => {
          this.layers = JSON.parse(res.data)
        })
      }
    },
    async fetchCity () {
      try {
        const { data } = await queryAllcity()
        this.city = data[0].children
      } catch (err) {
        throw (err)
      }
    },
    // 查询
    searchHandler () {
      this.showChart = true
      this.showTable = true
      this.handleChange()
      this.search()
    },

    async search () {
      this.loading = true
      try {
        let { data } = await queryPointList({
          ...this.searchForm
        })
        // 过滤耕地类型
        data = data.filter(item => {
          return !(/^01\d/.test(item.tdlylx))
        })

        if (this.searchForm.ldxb) {
          const ldxbResult = await this.getFeatrures()
          // 林地小班相交部分
          data = data.filter(item => {
            return ldxbResult.some(feature => {
              return feature.ydbh === item.ydbh
            })
          })
        }
        // 添加标记
        this.data = data.map(point => {
          return this.setMarker(point)
        })
        // 分段统计
        this.getRange()
        this.loading = false
      } catch (err) {
        this.loading = false
        throw (err)
      }
    },
    // 查询林地小班
    getFeatrures () {
      return new Promise(async (resolve, reject) => {
        try {
          const { data } = await spatialQuery({
            datasetname: '2',
            fieldtype: this.searchForm.ldxb
          })
          resolve(data)
        } catch (err) {
          reject(err)
        }
      })
    },
    setMarker (point) {
      return {
        ...point,
        coordinate: [ Number(point.jd), Number(point.wd) ],
        style: {
          fill: this.markerColor(point) || '#000',
          radius: 5
        }
        // src: MARKER_IMG[point.tdlylx.substring(0, 2)] || cd
      }
    },
    // 标记样式
    markerColor (data) {
      const element = data[this.chartType]
      for (const range of filedRange[this.chartType]) {
        if ((range.min === null || element >= range.min) && (range.max === null || element <= range.max)) {
          return range.color
        }
      }
    },
    clickPoint (marker) {
      // const items = [feature.get('data')]
      // this.showItem(items[0])
      // this.showItem(marker.items[0].ydbh)
    },
    // 行点击
    customRow (record) {
      return {
        on: {
          click: () => {
            // 高亮选中
            this.data = this.data.map(item => {
              if (item.ydbh === record.ydbh) {
                this.$refs.myMap.moveTo([ item.jd, item.wd ])
                return {
                  ...item,
                  style: {
                    fill: '#f00',
                    radius: 7
                  }
                }
              } else {
                return this.setMarker(item)
              }
            })
          }
        }
      }
    },
    async showItem (ydbh) {
      try {
        const { data } = await queryiQuery({
          ydbh: ydbh
        })
        this.markerInfo = data
        // this.showInfo = true
      } catch (err) {
        this.$message.error(err || '查询失败')
      }
    },

    // 切换统计值
    onChangeChart () {
      this.getRange()
      // 添加标记
      this.data = this.data.map(point => {
        return this.setMarker(point)
      })
    },
    getRange () {
      this.chartData = []
      const data = groupArrayByRange(this.data, filedRange[this.chartType], this.chartType)
      // 对象转数组
      Object.keys(data).forEach(key => {
        this.chartData.push(data[key])
      })
    },
    // 导出excel
    exportExcel () {
      if (!this.data.length) {
        this.$message.error('无导出数据')
        return false
      }
      const columns = []
      for (const key in this.data[0]) {
        if (Object.hasOwnProperty.call(this.data[0], key)) {
          columns.push({
            title: key,
            dataIndex: key
          })
        }
      }
      exportArrayToExcel({
        sheet: [
          {
            columns: columns,
            data: this.data,
            sheetName: this.searchForm.xzqdm
          }
        ],
        filename: '样点数据'
      })
    }
  },
  created () {
    this.initFilter()
    this.fetchCity()
    this.search()
  }
}
</script>

<style lang="less" scoped>
.page-view {
  position: relative;
  height: 100%;
  .map-view {
    position: absolute;
    top: -24px;
    right: -24px;
    bottom: -24px;
    left: -24px;
  }
  .result-icon {
    position: absolute;
    top: 40%;
    right: 0;
    .icon-item {
      margin: 8px 0;
      padding: 4px 8px;
      font-size: 20px;
      font-weight: bold;
      border-radius: 4px;
      background: #ffffff;
    }
    .active {
      color: @primary-color;
    }
  }
  .search {
    position: absolute;
    top: 0;
    right: 0;
    .condition {
      position: absolute;
      top: 46px;
      right: 0;
      padding: 16px;
      width: 600px;
      border-radius: 4px;
      background: #ffffff;
      box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.03);
    }
  }
  .chart-wrap {
    position: absolute;
    top: 0;
    left: 0;
    width: 400px;
    border-radius: 4px;
    background: #ffffff;
    box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.03);
    .heaer-title {
      display: flex;
      justify-content: space-between;
      padding: 0 14px;
      height: 40px;
      font-size: 16px;
      color: #222222;
      background: #ebeef5;
      line-height: 40px;
      .close {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.6);
        cursor: pointer;
      }
    }
    .chart-body {
      padding: 16px;
    }
    .chart-item {
      height: 240px;
    }
  }
}
.deawer-title {
  display: flex;
  justify-content: space-between;
}
/deep/ .ant-form-item {
  margin-bottom: 8px;
}
/deep/ .ant-descriptions-item-label {
  width: 150px;
}
.map-leg {
  position: absolute;
  right: 0;
  bottom: 24px;
  padding: 8px 16px;
  border-radius: 4px;
  background: #ffffff;
  .img {
    padding: 8px 0;
  }
  img {
    width: 30px;
  }
  span {
    padding-left: 8px;
  }
  .map-leg-icon {
    display: inline-block;
    width: 16px;
    height: 16px;
    vertical-align: middle;
  }
}
</style>
